//
//  LPActDetailResouseViewController.m
//  ShangHaiHuDongApp
//
//  Created by 刘应平 on 2017/7/2.
//  Copyright © 2017年 刘应平. All rights reserved.
//

#import "LPActDetailResouseViewController.h"
#import "LPActDetailResouceModel.h"
#import "LPActDetailResouceTableViewCell.h"
#import "LCustomAlertView.h"
#import "YTKKeyValueStore.h"
#import "LPWebWatchResouceViewController.h"
@interface LPActDetailResouseViewController ()<UITableViewDelegate,UITableViewDataSource,LCustomAlertDelegate,NSURLConnectionDelegate,NSURLConnectionDataDelegate>{
    NSURLConnection *_downConnection;
}
/**  tableView  */
@property (strong, nonatomic) UITableView  *tableView;
/**  数据  */
@property (strong, nonatomic) NSMutableArray  *dataSouce;
/**  page  */
@property (assign, nonatomic) NSInteger  page;
/** 滑动 */
@property (nonatomic, strong) ZJRefurbish *refurbish;
/**  jc  */
@property (strong, nonatomic) JCAlertView  *jcAlertView;
/**  选中的model  */
@property (strong, nonatomic) LPActDetailResouceModel  *chooseModel;

@end

@implementation LPActDetailResouseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.titlelabel.text = @"活动材料列表";
    __weak typeof(self) weakSelf = self;
    [self.refurbish headerToScollview:self.tableView Block:^{
        weakSelf.page = 1;
        [weakSelf netWorking_header];
        
    }];
    [self.refurbish footerToScollview:self.tableView Block:^{
        weakSelf.page ++;
        [weakSelf netWorking_footer];
    }];
    
    [self.tableView.mj_header beginRefreshing];
    [self layoutUI];
}
#pragma mark - 数据

//下拉刷新
- (void)netWorking_header{
    __weak typeof(self) weakSelf = self;
    NSString *page = [NSString stringWithFormat: @"%ld",(long)self.page];
    NSMutableDictionary *paramer = [NSMutableDictionary dictionary];
    paramer[@"AI_ID"] = self.model.ID;
    paramer[@"PAGE"] = page;
    paramer[@"COUNT"] = @"10";
    
    [NetWorkingManager postWithUrlString:[NetWorkingURL getactmactionActMaterial] Parameter:paramer Success:^(id object) {
       
        if ([object[@"STATE"] isEqualToString:@"20000"]) {
            NSArray *array = [object objectForKey:@"MAT_LIST"];
            weakSelf.dataSouce = [[NSArray yy_modelArrayWithClass:[LPActDetailResouceModel class] json:array] mutableCopy];
            [weakSelf.tableView reloadData];
            if (weakSelf.dataSouce.count == 0) {
                [LYEmptyManager showNoDataWithView:weakSelf.tableView];
            }
        }
        [weakSelf.tableView.mj_header endRefreshing];
    } Fail:^(id object) {
        [weakSelf.tableView.mj_header endRefreshing];
        if (weakSelf.dataSouce.count == 0) {
            [LYEmptyManager showLoadFailWithView:weakSelf.tableView managerBlock:^{
                [weakSelf.tableView.mj_header beginRefreshing];
            }];
        }else{
            [YJProgressHUD showMsgWithoutView:@"请求失败"];
        }
    }];
    
}

//上拉加载
- (void)netWorking_footer{
    __weak typeof(self) weakSelf = self;
    NSString *page = [NSString stringWithFormat: @"%ld",(long)self.page];
    NSMutableDictionary *paramer = [NSMutableDictionary dictionary];
    paramer[@"AI_ID"] = self.model.ID;
    paramer[@"PAGE"] = page;
    paramer[@"COUNT"] = @"10";
    
    [NetWorkingManager postWithUrlString:[NetWorkingURL getactmactionActMaterial] Parameter:paramer Success:^(id object) {
        if ([object[@"STATE"] isEqualToString:@"20000"]) {
            NSArray *array = [object objectForKey:@"MAT_LIST"];
            [weakSelf.dataSouce addObjectsFromArray:[NSArray yy_modelArrayWithClass:[LPActDetailResouceModel class] json:array]];
            [weakSelf.tableView reloadData];
        }
        [weakSelf.tableView.mj_footer endRefreshing];
    } Fail:^(id object) {
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
    
}

#pragma mark - 界面
- (void)layoutUI{
    
    [self.view addSubview:self.tableView];
}


#pragma mark - 私有方法


#pragma mark - LCustomAlertDelegate
- (void)lCustomAlertWithView:(LCustomAlertView *)view index:(NSInteger)index{
    if (index == 1) {
        [YJProgressHUD show:@"下载中..." inView:self.view mode:YJProgressModeLoading];
        /**  创建表  */
        YTKKeyValueStore *store = [[YTKKeyValueStore alloc] initDBWithName:RESOUCESURFACE];
        [store createTableWithName:RESOUCE_TABLE];
        //获取保存数据
        NSArray *downArray = [store getObjectById:ZJUSERINFORMODEL.ORG_ACCOUNT.ID fromTable:RESOUCE_TABLE];

        
        /**  获取本地文件路径  */
        NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
        /**  获取文件后缀  */
        NSArray *stringArray = [NSString getArrayFromString:self.chooseModel.FILE_PATH byString:@"."];
              /**  创建目录  */
        NSString *testDirectory = [documentsDirectory stringByAppendingString:@"/downResoucee"];
        /**  通过ID得到唯一标识  */
        NSString *testString = [NSString stringWithFormat:@"/%@.%@",self.chooseModel.ID,stringArray.lastObject];
        //  创建文件
        NSString *testPath = [testDirectory stringByAppendingPathComponent:testString];
        
        
        
        NSString *urlstring = [NSString stringWithFormat:@"%@/%@",DOWNFILE,self.chooseModel.FILE_PATH];
        urlstring = [urlstring stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url = [NSURL URLWithString:urlstring];
        //创建请求
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
//        _downConnection = [NSURLConnection connectionWithRequest:request delegate:self];
//        [_downConnection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
//        [_downConnection start];
        
        
        
        //方法二：发送一个异步请求
        [NSURLConnection sendAsynchronousRequest:request
                                           queue:[NSOperationQueue mainQueue]
                               completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                    [YJProgressHUD hide];
                   if (!connectionError) {
                       
                       NSData *doubi = data;
                       NSMutableArray *allArray = [NSMutableArray array];
                       [allArray addObjectsFromArray:downArray];
                       //  二进制流写入文件
                       NSFileManager *fileManger = [NSFileManager defaultManager];
                       //  创建目录
                       [fileManger createDirectoryAtPath:testDirectory withIntermediateDirectories:YES attributes:nil error:nil];
                       
                       //  写入文件
                       [fileManger createFileAtPath:testPath contents:doubi attributes:nil];
                       
                       /**  整合数据  */
                       NSDictionary *dataDic = @{@"resouce": testString};
                       [allArray addObject:dataDic];
                       
                       [store putObject:allArray withId:ZJUSERINFORMODEL.ORG_ACCOUNT.ID intoTable:RESOUCE_TABLE];
                       
                       LPWebWatchResouceViewController *vc = [LPWebWatchResouceViewController new];
                       vc.headLine = self.chooseModel.NAME;
                       vc.urlString = testPath;
                       [self.navigationController pushViewController:vc animated:YES];

                       
                       
                   } else {
                       [YJProgressHUD showMsgWithoutView:@"下载失败"];
                       
                   }
        }];
//
    }
    [self.jcAlertView dismissWithCompletion:nil];
}

#pragma mark - NSURLConnectionDataDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSInteger status = [(NSHTTPURLResponse *)response statusCode];
    
    if (status !=200) {
        
        [connection cancel];
        
    }
    
    // 获取文件总长度
    
    NSLog(@"文件长度%lld",response.expectedContentLength);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
//    _downloadFileLength += data.length; // 计算已经下载的文件总长度
//    
//    _downloadFileScale =_downloadFileLength*1.0/_totalFileLength; // 用当前已经下载文件长度除以下载文件总长度 ＝＝ 下载进度
    
    NSLog(@"下载长度%lu",(unsigned long)data.length);

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"下载完成");

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"下载失败");
}


#pragma mark - UITableViewDataSource,UITableViewDelegate
/**  返回组个数  */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
/**  返回cell个数  */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSouce.count;
}
/**  返回cell高度  */
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50 * [UIScreen zj_screenHScale];
}
/**  cell初始化  */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *weizhi = [NSString stringWithFormat:@"%ld-%ld",(long)indexPath.section,(long)indexPath.row];
    LPActDetailResouceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:weizhi];
    if (!cell) {
        cell = [[LPActDetailResouceTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:weizhi];
    }
    cell.model = self.dataSouce[indexPath.row];
    return cell;
}
/**  cell的点击事件  */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    LPActDetailResouceModel *model = self.dataSouce[indexPath.row];
     self.chooseModel = model;
    /**  获取本地文件路径  */
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    /**  创建表  */
    YTKKeyValueStore *store = [[YTKKeyValueStore alloc] initDBWithName:RESOUCESURFACE];
    [store createTableWithName:RESOUCE_TABLE];
   
    /**  获取文件后缀  */
    NSArray *stringArray = [NSString getArrayFromString:model.FILE_PATH byString:@"."];
    //获取保存数据
    NSArray *downArray = [store getObjectById:ZJUSERINFORMODEL.ORG_ACCOUNT.ID fromTable:RESOUCE_TABLE];
    /**  创建目录  */
    NSString *testDirectory = [documentsDirectory stringByAppendingString:@"/downResoucee"];
    /**  通过ID得到唯一标识  */
    NSString *testString = [NSString stringWithFormat:@"/%@.%@",model.ID,stringArray.lastObject];
    //  创建文件
    NSString *testPath = [testDirectory stringByAppendingPathComponent:testString];
    NSInteger flog = 0;
    NSDictionary *resouceDic;
    for (NSDictionary *dic  in downArray) {
        if ([dic[@"resouce"] isEqualToString:testString]) {
            flog = 1;
            resouceDic = dic;
        }
    }
    
    if (flog == 1) {
        /**  从本地判断，存在直接观看  */
        LPWebWatchResouceViewController *vc = [LPWebWatchResouceViewController new];
        vc.headLine = model.NAME;
        vc.urlString = testPath;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        /**  不存在就弹出下载  */
        [self downAlertView];
    
    }
    
    
}

- (void)downAlertView{
    LCustomAlertView *alert = [[LCustomAlertView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height) alertMessage:@"下载才能查看,是否下载" titlesArray:@[@"取消", @"确认"]];
    alert.delegate = self;
    self.jcAlertView = [[JCAlertView alloc] initWithCustomView:alert dismissWhenTouchedBackground:YES];
    [self.jcAlertView show];

}

#pragma mark - 懒加载
/**  初始化tableView  */
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, LP_TopHeight, self.view.bounds.size.width, self.view.bounds.size.height - LP_TopHeight) style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorColor = [UIColor clearColor];
        _tableView.tableFooterView = [UIView new];
        _tableView.backgroundColor = [UIColor themeGrayColor];
    }
    return _tableView;
}

- (NSMutableArray *)dataSouce{
    if (!_dataSouce) {
        _dataSouce = [NSMutableArray array];
    }
    return _dataSouce;
}
- (ZJRefurbish *)refurbish{
    if (!_refurbish) {
        _refurbish = [ZJRefurbish new];
    }
    return _refurbish;
}

- (LPActDetailResouceModel *)chooseModel{
    if (!_chooseModel) {
        _chooseModel = [LPActDetailResouceModel new];
    }
    return _chooseModel;
}
@end
